﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace XiaLastorm.Sharpshooter.Client
{
	/// <summary>
	/// MainWindow.xaml 的交互逻辑
	/// </summary>
	public partial class MainWindow : Window
	{
		/// <summary>
		/// 获取或设置正在和当前用户聊天的用户
		/// </summary>
		public Dictionary<User, ChatWindow> ChattingUsers { get; protected set; }

		System.Windows.Forms.NotifyIcon notifyIcon = new System.Windows.Forms.NotifyIcon();
		System.Windows.Forms.ContextMenuStrip contextMenuStrip = new System.Windows.Forms.ContextMenuStrip();
		System.Windows.Forms.ToolStripMenuItem item1 = new System.Windows.Forms.ToolStripMenuItem("登陆");
		System.Windows.Forms.ToolStripMenuItem item2 = new System.Windows.Forms.ToolStripMenuItem("注销");
		System.Windows.Forms.ToolStripMenuItem item3 = new System.Windows.Forms.ToolStripMenuItem("显示主窗口");
		System.Windows.Forms.ToolStripMenuItem item4 = new System.Windows.Forms.ToolStripMenuItem("退出程序");
		/// <summary>
		/// 生成 <see cref="MainWindow"/> class 的新实例。
		/// </summary>
		public MainWindow()
		{
			InitializeComponent();
			NotifyIcon();
			ContextMenuStrip();
			ChattingUsers = new Dictionary<User, ChatWindow>();

			this.Closed += delegate
			{
				notifyIcon.Dispose(); 
				if (Client.AppClient != null)
				{
					if (Client.AppClient.State == Client.ClientState.Opened)
					{
						if (Client.AppClient.IsOnline)
							Client.AppClient.LogOut();
						Client.AppClient.Close();
					}
					Client.AppClient = null;
				}
			};

			BtnLogIn.Click += delegate
			{
				try
				{
					if (Client.AppClient == null)
					{
						Client.AppClient = new Client(TbServerHost.Text);
						AddListenerToClient();
						TbServerHost.IsEnabled = false;
					}
					if (Client.AppClient.State == Sharpshooter.Client.Client.ClientState.BeforeOpen)
						Client.AppClient.Open();
					Client.AppClient.LogIn(TbUsername.Text, TbPassword.Password);
				}
				catch (Exception ex)
				{
					ResetApp();
					MessageBox.Show(ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
				}
			};
			BtnLogOut.Click += delegate
			{
				ResetApp();
			};
			TbUsername.TextChanged += delegate
			{
				if (TbUsername.Text != "用户名")
				{
					if (TbUsername.Text != "" && TbPassword.Margin == new Thickness(7))
					{
						TbPassword.Margin = new Thickness(7, 90, 7, 7);
						//TbPassword.Visibility = System.Windows.Visibility.Visible;
						(FindResource("TbPasswordAppear") as Storyboard).Begin();
					}
					else if (TbUsername.Text == "" && TbPassword.Margin == new Thickness(7, 100, 7, 7))
					{
						(FindResource("TbPasswordDisappear") as Storyboard).Begin();
						TbUsername.Text = "用户名";
						TbUsername.SelectAll();
					}
				}
			};
		}



		/// <summary>
		/// 对客户端添加事件处理程序
		/// </summary>
		protected void AddListenerToClient()
		{
			Client.AppClient.LogAdded += new EventHandler<LogAddedEventArgs>((sender, e) =>
			{
				Dispatcher.BeginInvoke(new Action(() =>
				{
					System.Diagnostics.Debug.WriteLine(e.AddedLog.ToString());
				}));
			});
			Client.AppClient.ChatLogAdded += new EventHandler<ChatLogAddedEventArgs>((sender, e) =>
			{
				Dispatcher.BeginInvoke(new Action(() =>
				{
					if (e.AddedChatLog.To == Client.AppClient.User)
					{
						if (!ChattingUsers.ContainsKey(e.AddedChatLog.From))
						{
							CreateChatWindow(e.AddedChatLog.From);
						}
						ChattingUsers[e.AddedChatLog.From].AddChatLog(e.AddedChatLog);
					}
					else if (e.AddedChatLog.From == Client.AppClient.User)
					{
						if (ChattingUsers.ContainsKey(e.AddedChatLog.To))
						{
							ChattingUsers[e.AddedChatLog.To].AddChatLog(e.AddedChatLog);
						}
					}
				}));
			});
			Client.AppClient.UserLoggedIn += new EventHandler<UserEventArgs>((sender, e) =>
			{
				Dispatcher.BeginInvoke(new Action(() =>
				{
					TbUsername.IsEnabled = false;
					BtnLogIn.IsEnabled = false;
					BtnLogOut.IsEnabled = true;
					TBlockUsername.Text = Client.AppClient.User.ToString();
					PanelLogIn.Visibility = Visibility.Visible;
					PanelNormal.Visibility = Visibility.Visible;
					(FindResource("PanelLoginAppear") as Storyboard).Begin();
					item1.Visible = false;
					item2.Visible = true;
				}));
			});
			Client.AppClient.UserLoggedOut += new EventHandler<UserEventArgs>((sender, e) =>
			{
				Dispatcher.BeginInvoke(new Action(() =>
				{
					ResetApp();
				}));
			});
			Client.AppClient.FriendsListChanged += new EventHandler((sender, e) =>
			{
				Dispatcher.BeginInvoke(new Action(() =>
				{
					/* 当多个用户（包括自己）同时关闭客户端时，会引发UserLoggedOut和FriendListChanged事件，
					 * 有可能先执行ResetApp()，再执行这里的语句，
					 * 所以不能保证Client.AppClient不为null
					 * */
					if (Client.AppClient != null)
					{
						LbFriends.ItemsSource = Client.AppClient.Friends;
						for (int i = 0; i < LbFriends.Items.Count; ++i)
						{
							(LbFriends.ItemContainerGenerator.ContainerFromIndex(i) as ListBoxItem).MouseDoubleClick += (sender2, e2) =>
							{
								User user = LbFriends.ItemContainerGenerator.ItemFromContainer(sender2 as ListBoxItem) as User;
								if (ChattingUsers.ContainsKey(user))
								{
									ChattingUsers[user].Activate();
								}
								else
								{
									CreateChatWindow(user);
								}
							};
						}
					}
				}));
			});
			Client.AppClient.ErrorOccured += new EventHandler<ErrorEventArgs>((sender, e) =>
			{
				Dispatcher.BeginInvoke(new Action(() =>
				{
					MessageBox.Show(e.Error, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
				}));
			});
			Client.AppClient.ConnectionLost += delegate
			{
				Dispatcher.BeginInvoke(new Action(() =>
				{
					ResetApp();
					MessageBox.Show("与服务器丢失连接", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
				}));
			};
		}

		/// <summary>
		/// 新建聊天窗口
		/// </summary>
		/// <param name="chatTo">The chat to.</param>
		public void CreateChatWindow(User chatTo)
		{
			if (chatTo == null)
				throw new ArgumentNullException("chatTo");
			ChatWindow window = new ChatWindow(chatTo);
			ChattingUsers.Add(chatTo, window);
			window.Closed += (sender, e) =>
			{
				ChattingUsers.Remove((sender as ChatWindow).ChatTo);
			};
			Dispatcher.BeginInvoke(new Action(() =>
			{
				window.Show();
			}));
		}


		/// <summary>
		/// 重置程序
		/// </summary>
		protected void ResetApp()
		{
			while (ChattingUsers.Count > 0)
			{
				ChattingUsers.Values.First().Close();
			}
			TbUsername.IsEnabled = true;
			BtnLogIn.IsEnabled = true;
			BtnLogOut.IsEnabled = false;
			LbFriends.ItemsSource = null;
			if (Client.AppClient != null)
			{
				if (Client.AppClient.State == Client.ClientState.Opened)
				{
					if (Client.AppClient.UserState == Client.UserStateKind.Online)
					{
						Client.AppClient.LogOut();
					}
					Client.AppClient.Close();
				}
				Client.AppClient = null;
			}
			TbServerHost.IsEnabled = true;
			PanelLogIn.Visibility = Visibility.Visible;
			PanelNormal.Visibility = Visibility.Visible;
			(FindResource("PanelLoginDisappear") as Storyboard).Begin();
			item1.Visible = true;
			item2.Visible = false;
		}

		private void TbUsername_PreviewMouseUp(object sender, RoutedEventArgs e)
		{
			if (TbUsername.Text == "用户名") TbUsername.Text = "";
			//e.Handled = true;
		}

		private void Button_Click(object sender, RoutedEventArgs e)
		{
			this.Close();
		}

		private void Button_Click_2(object sender, RoutedEventArgs e)
		{
			this.WindowState = System.Windows.WindowState.Minimized;
			this.Hide();
			item3.Visible = true;
		}

		private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
		{
			this.DragMove();
			//LoginButton.Focus();
		}

		private void NotifyIcon()
		{
			//this.notifyIcon = new System.Windows.Forms.NotifyIcon();
			this.notifyIcon.BalloonTipText = "很明显你点的是右键！";
			this.notifyIcon.Text = "这个什么时候出现？";
			this.notifyIcon.Icon = Properties.Resources.S;
			this.notifyIcon.Visible = true;

			notifyIcon.MouseDoubleClick += (sender, e) =>
			{
				if (e.Button == System.Windows.Forms.MouseButtons.Left)
				{
					this.Show();
					this.WindowState = System.Windows.WindowState.Normal;
					this.Activate();
				}
				else if (e.Button == System.Windows.Forms.MouseButtons.Right)
				{
					//this.notifyIcon.ShowBalloonTip(1000);
				}
			};			
		}

		private void ContextMenuStrip()
		{
			item1.Click += delegate
			{
				this.Show();
				this.WindowState = System.Windows.WindowState.Normal;
				this.Activate();
			};
			item2.Click += delegate { ResetApp(); };
			item3.Click += delegate
			{
				this.Show();
				this.WindowState = System.Windows.WindowState.Normal;
				this.Activate();
				item3.Visible = false;
			};
			item4.Click += delegate { this.Close(); };
			contextMenuStrip.Items.Add(item1);
			contextMenuStrip.Items.Add(item2);
			contextMenuStrip.Items.Add(item3);
			contextMenuStrip.Items.Add(item4);
			item2.Visible = false;
			item3.Visible = false;			
			this.notifyIcon.ContextMenuStrip = contextMenuStrip;
		}
	}
}
